// Fill out your copyright notice in the Description page of Project Settings.


#include "Character/AuraCharacter.h"

#include "AbilitySystemComponent.h"
#include "AbilitySystem/AuraAbilitySystemComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/PawnMovementComponent.h"
#include "Player/AuraHUD.h"
#include "Player/AuraPlayerController.h"
#include "Player/AuraPlayerState.h"

AAuraCharacter::AAuraCharacter()
{
	GetCharacterMovement()->bOrientRotationToMovement = true;
	GetCharacterMovement()->RotationRate = FRotator(0.f, 400.f, 0.f);
	GetCharacterMovement()->bConstrainToPlane = true;
	GetCharacterMovement()->bSnapToPlaneAtStart = true;

	bUseControllerRotationPitch = false;
	bUseControllerRotationYaw = false;
	bUseControllerRotationRoll = false;

	RoleClass = ERoleClass::Elementalist;
}

// 忽略网络因素是先初始化UI在初始化技能
void AAuraCharacter::PossessedBy(AController* NewController)
{
	Super::PossessedBy(NewController);
	
	InitAbilityActorInfo();

	/** 设置所有者 */
	SetOwner(NewController);

	/** 初始化角色技能 */
	InitCharacterAbilities();
}

void AAuraCharacter::OnRep_PlayerState()
{
	Super::OnRep_PlayerState();

	InitAbilityActorInfo();
}

void AAuraCharacter::InitCharacterAbilities()
{
	UAuraAbilitySystemComponent* AuraASC = CastChecked<UAuraAbilitySystemComponent>(GetAbilitySystemComponent());
	// 是否是服务端, 服务端才能授予ASC能力
	if (HasAuthority())
	{
		AuraASC->AddCharacterAbilities(StartUpAbilityClasses);
		AuraASC->AddCharacterPassiveAbilities(StartUpPassiveAbilityClasses);
	}
}

int32 AAuraCharacter::GetLevel()
{
	const AAuraPlayerState* AuraPlayerState = GetPlayerState<AAuraPlayerState>();
	check(AuraPlayerState);
	return AuraPlayerState->GetCharacterLevel();
}

void AAuraCharacter::InitAbilityActorInfo()
{
	AAuraPlayerState* AuraPlayerState = GetPlayerState<AAuraPlayerState>();
	check(AuraPlayerState);
	//从PlayerState获取ASC和AS
	AbilitySystemComponent = AuraPlayerState->GetAbilitySystemComponent();
	AttributeSet = AuraPlayerState->GetAttributeSet();
	AbilitySystemComponent->InitAbilityActorInfo(AuraPlayerState, this); //初始化ASC信息,即初始化组件的Owner(拥有者)和Avatar(化身,代理)

	/** 触发技能信息设置 */
	Cast<UAuraAbilitySystemComponent>(AbilitySystemComponent)->SetAbilitySystemWorkInfo();

	/** 从Control获取HUD并调用函数初始化HUD */
	if (AAuraPlayerController* AuraPlayerController = Cast<AAuraPlayerController>(GetController()))
	//用if不用断言,因为多人游戏们持有其他玩家的pawn但并不持有其他玩家的Controller,用断言肯定会触发
	{
		if (AAuraHUD* AuraHUD = Cast<AAuraHUD>(AuraPlayerController->GetHUD()))
		{
			AuraHUD->InitOverlay(AuraPlayerController, AuraPlayerState, AbilitySystemComponent, AttributeSet);
		}
	}
	/** 通过GE初始化角色属性 */
	InitDefaultAttributes();
}

void AAuraCharacter::BeginPlay()
{
	Super::BeginPlay();
}
